#!/bin/bash

# XCQuant数据库备份脚本
# 作者: XCQuant Team
# 版本: 1.0

set -e

# 配置变量
BACKUP_DIR="/backups"
DB_HOST="postgres"
DB_PORT="5432"
DB_NAME="xcquant"
DB_USER="xcquant"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-30}

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 创建备份目录
mkdir -p $BACKUP_DIR

# 数据库备份
backup_database() {
    log "开始备份数据库..."
    
    BACKUP_FILE="$BACKUP_DIR/xcquant_db_$DATE.sql.gz"
    
    # 执行备份
    if pg_dump -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME | gzip > $BACKUP_FILE; then
        log "数据库备份成功: $BACKUP_FILE"
        
        # 验证备份文件
        if [ -s "$BACKUP_FILE" ]; then
            log "备份文件验证成功，大小: $(du -h $BACKUP_FILE | cut -f1)"
        else
            log "错误: 备份文件为空"
            rm -f $BACKUP_FILE
            exit 1
        fi
    else
        log "错误: 数据库备份失败"
        exit 1
    fi
}

# 配置文件备份
backup_configs() {
    log "开始备份配置文件..."
    
    CONFIG_BACKUP_FILE="$BACKUP_DIR/xcquant_config_$DATE.tar.gz"
    
    # 备份配置文件
    tar -czf $CONFIG_BACKUP_FILE \
        -C /app \
        config/ \
        deploy/ \
        2>/dev/null || true
    
    if [ -s "$CONFIG_BACKUP_FILE" ]; then
        log "配置文件备份成功: $CONFIG_BACKUP_FILE"
    else
        log "警告: 配置文件备份为空或失败"
    fi
}

# 清理旧备份
cleanup_old_backups() {
    log "清理 $RETENTION_DAYS 天前的备份文件..."
    
    # 删除旧的数据库备份
    find $BACKUP_DIR -name "xcquant_db_*.sql.gz" -mtime +$RETENTION_DAYS -delete 2>/dev/null || true
    
    # 删除旧的配置备份
    find $BACKUP_DIR -name "xcquant_config_*.tar.gz" -mtime +$RETENTION_DAYS -delete 2>/dev/null || true
    
    log "旧备份清理完成"
}

# 备份统计
backup_stats() {
    log "备份统计信息:"
    log "- 数据库备份文件数量: $(find $BACKUP_DIR -name "xcquant_db_*.sql.gz" | wc -l)"
    log "- 配置备份文件数量: $(find $BACKUP_DIR -name "xcquant_config_*.tar.gz" | wc -l)"
    log "- 备份目录总大小: $(du -sh $BACKUP_DIR | cut -f1)"
}

# 发送通知
send_notification() {
    local status=$1
    local message=$2
    
    # 这里可以添加邮件、微信、Telegram等通知逻辑
    log "通知: $status - $message"
}

# 主函数
main() {
    log "开始执行备份任务..."
    
    # 检查数据库连接
    if ! pg_isready -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME >/dev/null 2>&1; then
        log "错误: 无法连接到数据库"
        send_notification "ERROR" "数据库连接失败"
        exit 1
    fi
    
    # 执行备份
    backup_database
    backup_configs
    cleanup_old_backups
    backup_stats
    
    log "备份任务完成"
    send_notification "SUCCESS" "备份任务成功完成"
}

# 错误处理
trap 'log "备份过程中发生错误"; send_notification "ERROR" "备份任务失败"; exit 1' ERR

# 执行主函数
main "$@"